package cn.net.springboot.netty.learn.socket;

import io.netty.util.CharsetUtil;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Chris
 * @version 1.0.0
 * @date 2019/05/17
 * @since 1.0.0
 */
public class PlainOioServer {

    public static void server(int port) throws IOException {
        final ServerSocket socket = new ServerSocket(port);
        try {
            for (; ; ) {
                Socket clientSocket = socket.accept();
                System.out.println("Accepted connection from " + clientSocket);
                new Thread(() -> {
                    try (OutputStream out = clientSocket.getOutputStream()) {
                        out.write("Hi!".getBytes(CharsetUtil.UTF_8));
                        clientSocket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            clientSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            server(9088);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
